import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/match/zq_odds_entity.dart';
import 'package:ball_lion/entity/match/secret_info_entity.dart';
import 'package:ball_lion/module/widget/history_label.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/constant.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/utils/mode_config.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/widgets/card.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';

class SecretItem extends StatelessWidget {
  const SecretItem(
      {super.key,
      required this.secret,
      this.margin,
      this.showHistory = false,
      this.onChange})
      : count = null,
        inDetail = false;

  const SecretItem.detail(
      {super.key,
      this.showHistory = false,
      this.onChange,
      this.secret,
      this.margin,
      this.count})
      : inDetail = true;

  final SecretInfoEntity? secret;
  final EdgeInsets? margin;
  final bool inDetail;
  final bool showHistory;
  final int? count;
  final ValueChanged<bool>? onChange;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (Get.currentRoute == Routes.navigation ||
            Get.currentRoute == Routes.secretList) {
          Get.toNamed(
              secret?.sportsId == 1
                  ? Routes.zqMatchDetail
                  : Routes.lqMatchDetail,
              arguments: secret?.matchId,
              parameters: {"tabName": Constant.baoliao});
        }
      },
      child: Column(
        children: [
          Block(
            cardStyle:
                CardStyle(margin: margin, padding: const EdgeInsets.all(12)),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                if (secret?.canRead == false && !inDetail)
                  DefaultTextStyle(
                    style: const TextStyle(fontSize: 11, color: Colours.grey66),
                    child: Row(
                      children: [
                        QsText(secret?.leagueName ?? ""),
                        Container(width: 8),
                        QsText(secret?.dcNo ?? ""),
                        const Spacer(),
                        QsText(secret?.timeShow ?? "")
                      ],
                    ),
                  ),
                if (!inDetail || secret?.canRead == true) ...[
                  Container(height: secret?.canRead == true ? 4 : 12),
                  RichText(
                    textAlign: TextAlign.justify,
                    text: TextSpan(
                        style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w500,
                            color: Colours.text),
                        children: [
                          WidgetSpan(
                              child: SizedBox(
                            height: 20,
                            width: 28,
                            child: Stack(
                                alignment: AlignmentDirectional.center,
                                children: [
                                  Image.asset(
                                      Utils.getImgPath("secret_head_back.png"),
                                      height: 20,
                                      width: 28),
                                  const Positioned(
                                      bottom: 3.6,
                                      child: QsText("情报",
                                          fontSize: 10,
                                          color: Colours.white,
                                          fontWeight: FontWeight.w500))
                                ]),
                          ).paddingOnly(right: 8)),
                          TextSpan(
                              text: secret?.canRead == true
                                  ? (secret?.title?.split("").join("\u200A") ??
                                      "")
                                  : "${secret?.home} VS ${secret?.away}")
                        ]),
                  ),
                  Container(height: 8),
                ],
                if (secret?.canRead == true) ...[
                  Html(
                      shrinkWrap: true,
                      data: "<body>${secret?.content}</body>",
                      style: {
                        "body": Style(
                            margin: Margins.all(0),
                            fontSize: FontSize(14),
                            color: const Color(0xFF444444),
                            letterSpacing: -0.3,
                            lineHeight: const LineHeight(1.6),
                            textAlign: TextAlign.justify),
                      }),
                  if (secret?.firstOdds.hasValue == true &&
                      secret?.realOdds.hasValue == true &&
                      ModeConfig.secretOdds)
                    odds().paddingOnly(bottom: 8, top: 4),
                  if (!inDetail) _matchInfoWidget().paddingOnly(top: 8),
                  Container(
                    margin: const EdgeInsets.only(top: 8),
                    alignment: Alignment.centerLeft,
                    constraints: const BoxConstraints(maxWidth: 180),
                    clipBehavior: Clip.antiAlias,
                    decoration:
                        BoxDecoration(borderRadius: BorderRadius.circular(4)),
                    child: CachedNetworkImage(
                      width: 180,
                      fit: BoxFit.cover,
                      imageUrl: secret?.image?.trim() ?? "",
                      placeholder: (context, url) => Container(),
                      errorWidget: (context, url, error) => Container(),
                    ),
                  )
                ] else if (secret?.canRead == false || count != null) ...[
                  Container(
                      height: 76,
                      width: Get.width,
                      decoration: BoxDecoration(
                          color: Colours.main.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(color: Colours.main, width: 0.5)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Image.asset(
                              width: 16, Utils.getImgPath("ai_lock.png")),
                          Container(width: 4),
                          QsText("开通查看${count != null ? "$count篇" : "所有"}情报",
                              color: Colours.main, fontWeight: FontWeight.w500),
                          Container(width: 4),
                          Image.asset(Utils.getImgPath("arrow_right_36.png"),
                              width: 12, color: Colours.main)
                        ],
                      ).tap(() async {
                        if (Get.currentRoute == Routes.navigation ||
                            Get.currentRoute == Routes.secretList) {
                          await Get.toNamed(Routes.secretPay, parameters: {
                            "roomId": Get.parameters['roomId'] ?? ""
                          })?.then((value) => onChange?.call(true));
                        } else {
                          Utils.onEvent('bs_bl_ktqb');
                          await Get.toNamed(Routes.secretList)
                              ?.then((value) => onChange?.call(true));
                        }
                      }))
                ],
                Container(height: 12),
                Row(
                  children: [
                    if (secret?.publishTime != null)
                      QsText(
                          Utils.formatTime(
                              DateTime.parse(secret?.publishTime ?? "")
                                  .millisecondsSinceEpoch),
                          needCenter: true,
                          fontSize: 12,
                          color: Colours.grey66),
                    const Spacer(),
                    if (secret?.matchTime != null &&
                        secret?.publishTime != null &&
                        DateTime.parse(secret!.matchTime!)
                                .isAfter(DateTime.parse(secret!.freeTime!)) ==
                            true)
                      QsText("限时免费",
                          needCenter: true, fontSize: 12, color: Colours.main)
                  ],
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _matchInfoWidget() {
    return Stack(
      alignment: AlignmentDirectional.centerEnd,
      children: [
        Container(
            width: Get.width,
            padding: const EdgeInsets.fromLTRB(10, 4, 10, 5),
            decoration: BoxDecoration(
                color: Colours.greyF5F7FA,
                borderRadius: BorderRadius.circular(5)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                QsText("[${secret?.sportsId == 1 ? "足" : "篮"}]\u2000",
                    fontSize: 12, color: Colours.grey666666),
                QsText(
                  "${DateTime.parse(secret?.matchTime ?? '').formatedString("MM/dd HH:mm") ?? "时间暂无"}\u2000",
                  fontSize: 12,
                  color: Colours.grey666666,
                  height: 1.5,
                ),
                Container(
                    width: 0.5,
                    height: 10,
                    alignment: Alignment.center,
                    color: Colours.greyE0E1E5),
                QsText(
                  "\u2000${secret?.leagueName ?? "未知联赛"}\u2000",
                  fontSize: 12,
                  color: Colours.grey666666,
                ),
                Flexible(
                  child: QsText(secret?.home ?? "主队未知",
                      fontSize: 12, color: Colours.grey666666, maxLines: 1),
                ),
                const QsText("\u2000"),
                const QsText("vs", fontSize: 12, color: Colours.grey666666),
                const QsText("\u2000"),
                Flexible(
                  child: QsText(secret?.away ?? "客队未知",
                      fontSize: 12, color: Colours.grey666666, maxLines: 1),
                ),
              ],
            )),
        Positioned(child: HistoryLabel.secret(state: secret?.status))
      ],
    );
  }

  Widget odds() {
    return DefaultTextStyle(
      style: const TextStyle(fontSize: 12),
      child: Container(
        clipBehavior: Clip.antiAlias,
        padding: const EdgeInsets.all(2),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(4), color: Colours.greyF2F3F7),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(children: formSingleLine("初", secret?.firstOdds ?? [])),
            Container(height: 2),
            Row(children: formSingleLine("即", secret?.realOdds ?? []))
          ],
        ),
      ),
    );
  }

  List<Widget> formSingleLine(String title, List<OddsData> dataList) {
    List<Widget> list = [
      QsText(title, color: Colours.grey99).center,
      Container(),
      Container(),
      Container()
    ];
    for (var element in dataList) {
      switch (element.i) {
        case "d":
        case "s":
        case "z":
          list.replaceRange(1, 2, [formValue(element.o, element.st)]);
          break;
        case "x":
        case "k":
        case "f":
          list.replaceRange(3, 4, [formValue(element.o, element.st)]);
          break;
        case "p":
          list.replaceRange(2, 3, [formValue(element.o, element.st)]);
          break;
      }
    }
    return list
        .where((element) => element is! Container)
        .map((e) => Container(
              width: 62,
              height: 22,
              decoration: const BoxDecoration(color: Colours.white, boxShadow: [
                BoxShadow(
                    offset: Offset(0, 1),
                    blurRadius: 3,
                    color: Color(0x060F499F))
              ]),
              child: e,
            ))
        .toList()
        .insertEvery(Container(width: 2));
  }

  String remain2(String? data) {
    return data.noValue ? "" : double.parse(data!).toStringAsFixed(2);
  }

  Widget formValue(data, status) {
    String text = "";
    Widget? asset;
    Color color = Colours.text;
    if (status == 0) {
      text = remain2(data);
    } else if (status == 1) {
      text = remain2(data);
      color = Colours.redF13333;
      asset = Image.asset(height: 9, Utils.getImgPath("up_arrow_red.png"));
    } else if (status == 2) {
      text = remain2(data);
      color = Colours.green;
      asset = Image.asset(height: 9, Utils.getImgPath("down_arrow_green.png"));
    } else {
      text = remain2(data);
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [QsText(text, color: color), if (asset != null) asset],
    );
  }
}
